package com.gzlg.hospital.controller;

import com.gzlg.hospital.pojo.*;
import com.gzlg.hospital.service.AdminService;


import com.gzlg.hospital.service.DoctorService;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private DoctorService doctorService;

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);
    //
    @GetMapping("/home")
    public String adminHome() {
        return "Admin/home";
    }

    // 医生管理
    @GetMapping("/doctor/list")
    public String listDoctors(@RequestParam(required = false) String name, @RequestParam(required = false) String id_card, Model model) {
        List<Doctor> doctors;
        if ((name != null && !name.isEmpty()) || (id_card != null && !id_card.isEmpty())) {
            doctors = adminService.findDoctorsByNameAndIdCard(name, id_card);
        } else {
            doctors = adminService.findAllDoctors();
        }
        model.addAttribute("doctors", doctors);
        return "Admin/doctor_list";
    }

    @GetMapping("/doctor/add")
    public String showDoctorForm(Model model) {
        model.addAttribute("doctor", new Doctor());
        return "Admin/doctor_form";
    }

    @PostMapping("/doctor/save")
    public String saveDoctor(@ModelAttribute Doctor doctor, RedirectAttributes redirectAttributes) {
        if (doctor.getId() == null) {
            adminService.saveDoctor(doctor);
            redirectAttributes.addFlashAttribute("message", "医生添加成功");
        } else {
            adminService.updateDoctor(doctor);
            redirectAttributes.addFlashAttribute("message", "医生信息更新成功");
        }
        return "redirect:/admin/doctor/list";
    }

    @GetMapping("/doctor/edit/{id}")
    public String editDoctor(@PathVariable Integer id, Model model) {
        model.addAttribute("doctor", adminService.findDoctorById(id));
        return "Admin/doctor_form";
    }

    @GetMapping("/doctor/delete/{id}")
    public String deleteDoctor(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        adminService.deleteDoctorById(id);
        redirectAttributes.addFlashAttribute("message", "医生删除成功");
        return "redirect:/admin/doctor/list";
    }

    //患者用户管理
    // 患者管理
    @GetMapping("/patient/list")
    public String listPatients(@RequestParam(required = false) String name, @RequestParam(required = false) String id_card, Model model) {
        List<Patient> patients;
        if ((name != null && !name.isEmpty()) || (id_card != null && !id_card.isEmpty())) {
            patients = adminService.findPatientsByNameAndIdCard(name, id_card);
        } else {
            patients = adminService.findAllPatients();
        }
        model.addAttribute("patients", patients);
        return "Admin/patient_list";
    }

    // 显示添加表单
    @GetMapping("/patient/add")
    public String showAddForm(Model model) {
        model.addAttribute("patient", new Patient());
        return "Admin/patient_form";
    }

    // 显示编辑表单
    @GetMapping("/edit/{id}")
    public String editPatient(@PathVariable Integer id, Model model) {
        model.addAttribute("patient", adminService.findPatientById(id));
        return "Admin/patient_form";
    }

    // 保存或更新患者
    @PostMapping("/patient/save")
    public String savePatient(@ModelAttribute Patient patient) {
        if (patient.getRole() == null || patient.getRole().isEmpty()) {
            patient.setRole("patient");
        }
        if (patient.getId() == null) {
            adminService.savePatient(patient);
        } else {
            adminService.updatePatient(patient);
        }
        return "redirect:/admin/patient/list";
    }

    // 删除患者
    @GetMapping("/delete/{id}")
    public String deletePatient(@PathVariable Integer id) {
        adminService.deletePatientById(id);
        return "redirect:/admin/patient/list";
    }

    //根据患者id查询患者的挂号记录
    @GetMapping("/registration/list")
    public String searchRegistrationsByPatient_id(
            @RequestParam(name = "patient_id", required = false) Integer patient_id,
            Model model) {

        logger.info("searchRegistrationsByPatient_id method called with patient_id: {}", patient_id);

        if (patient_id != null && patient_id > 0) {
            List<Registration> registrations = adminService.getRegistrationsByPatient_id(patient_id);
            logger.info("Found {} registrations for patient_id: {}", registrations.size(), patient_id);
            model.addAttribute("registrations", registrations);
            model.addAttribute("patient_id", patient_id);
        } else {
            logger.info("No valid patient_id provided.");
        }

        return "Admin/registration_list";
    }







    // 药品管理
    @GetMapping("/drug/list")
    public String listDrugs(Model model) {
        model.addAttribute("drugs", adminService.findAllPharmaceuticals());
        return "Admin/drug_list";
    }

    @GetMapping("/drug/add")
    public String showDrugForm(Model model) {
        model.addAttribute("drug", new Pharmaceutical());
        return "Admin/drug_form";
    }

    @PostMapping("/drug/save")
    public String saveDrug(@ModelAttribute("drug") Pharmaceutical drug, RedirectAttributes redirectAttributes) {
        if (drug.getId() == null) {
            adminService.savePharmaceutical(drug);
            redirectAttributes.addFlashAttribute("message", "药品添加成功");
        } else {
            adminService.updatePharmaceutical(drug);
            redirectAttributes.addFlashAttribute("message", "药品信息更新成功");
        }
        return "redirect:/admin/drug/list";
    }

    @GetMapping("/drug/edit/{id}")
    public String editDrug(@PathVariable Integer id, Model model) {
        model.addAttribute("drug", adminService.findPharmaceuticalById(id));
        return "Admin/drug_form";
    }

    @GetMapping("/drug/delete/{id}")
    public String deleteDrug(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        adminService.deletePharmaceuticalById(id);
        redirectAttributes.addFlashAttribute("message", "药品删除成功");
        return "redirect:/admin/drug/list";
    }

    @GetMapping("/drug/search")
    public String searchDrugs(@RequestParam(name = "name", defaultValue = "") String name,
                              @RequestParam(name = "manufacturer", defaultValue = "") String manufacturer,
                              Model model) {
        List<Pharmaceutical> drugs = adminService.findPharmaceuticalsByNameAndManufacturer(name, manufacturer);
        model.addAttribute("drugs", drugs);
        return "Admin/drug_list";
    }


    // 检查项目管理页面
    @GetMapping("/checkItems")
    public String listCheckItems(Model model) {
        model.addAttribute("checkItems", adminService.findAllCheckItems());
        return "Admin/checkitem_list";
    }

    // 新增检查项目页面
    @GetMapping("/checkItem/add")
    public String showCheckItemForm(Model model) {
        model.addAttribute("checkItem", new CheckItem());
        return "Admin/checkitem_form";
    }

    // 保存检查项目
    @PostMapping("/checkItem/save")
    public String saveCheckItem(@ModelAttribute CheckItem checkItem, RedirectAttributes redirectAttributes) {
        if (checkItem.getId() == null) {
            adminService.saveCheckItem(checkItem);
            redirectAttributes.addFlashAttribute("message", "检查项目添加成功");
        } else {
            adminService.updateCheckItem(checkItem);
            redirectAttributes.addFlashAttribute("message", "检查项目更新成功");
        }
        return "redirect:/admin/checkItems";
    }

    // 编辑检查项目
    @GetMapping("/checkItem/edit/{id}")
    public String editCheckItem(@PathVariable Integer id, Model model) {
        model.addAttribute("checkItem", adminService.findCheckItemById(id));
        return "Admin/checkitem_form";
    }

    // 删除检查项目
    @GetMapping("/checkItem/delete/{id}")
    public String deleteCheckItem(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        adminService.deleteCheckItemById(id);
        redirectAttributes.addFlashAttribute("message", "检查项目删除成功");
        return "redirect:/admin/checkItems";
    }

    // 检查项目搜索

    @GetMapping("/checkItems/search")
    public String searchCheckItems(@RequestParam(name = "name", defaultValue = "") String name,
                                   @RequestParam(name = "department", defaultValue = "") String department,
                                   Model model) {
        List<CheckItem> checkItems = adminService.findCheckItemsByNameAndDepartment(name, department);
        model.addAttribute("checkItems", checkItems);
        return "Admin/checkitem_list";
    }



    // 排班管理

    @GetMapping("/schedule/list")
    public String showScheduleList(Model model) {
        List<Schedule> schedules = adminService.findAllSchedules(); // 获取所有排班记录
        model.addAttribute("schedules", schedules);
        return "Admin/schedule_list";
    }



    @GetMapping("/schedule/add")
    public String showAddScheduleForm(@RequestParam(value = "doctor_id", required = false) Integer doctor_id, @RequestParam(value = "doctor_name", required = false) String doctor_name, Model model) {
        Schedule schedule = new Schedule();
        List<String> departments = adminService.getAllDepartments();
        model.addAttribute("departments", departments);
        // 验证参数一致性：如果其中一个参数存在，另一个也必须存在
        if ((doctor_id != null && doctor_name == null) || (doctor_id == null && doctor_name != null)) {
            logger.info("Received doctor_id: {}, doctor_name: {}", doctor_id, doctor_name);

        } else if (doctor_id != null) {
            schedule.setDoctor_id(doctor_id);
            schedule.setDoctor_name(doctor_name);
        }
        model.addAttribute("schedule", schedule);
        model.addAttribute("doctors", adminService.findAllDoctors());
        return "Admin/schedule_add";
    }



    @GetMapping("/schedule/add/{doctorId}")
    public String showAddScheduleFormForDoctor(@PathVariable Integer doctorId, Model model) {
        Doctor doctor = adminService.findDoctorById(doctorId);
        Schedule schedule = new Schedule();
        schedule.setDoctor_id(doctorId);
        schedule.setDoctor_name(doctor.getName());

        List<String> departments = adminService.getAllDepartments();
        model.addAttribute("departments", departments);
        model.addAttribute("schedule", schedule);
        return "Admin/schedule_add";
    }

    @PostMapping("/schedule/save")
    public String saveSchedule(@ModelAttribute Schedule schedule, RedirectAttributes redirectAttributes) {
        logger.info("接收到保存请求，排班信息: {}", schedule);

        if (schedule.getId() != null) {
            // 更新现有记录
            adminService.update(schedule);
            redirectAttributes.addFlashAttribute("message", "排班信息更新成功");
        } else {
            // 插入新记录
            adminService.saveSchedule(schedule);
            redirectAttributes.addFlashAttribute("message", "排班信息添加成功");
        }

        return "redirect:/admin/schedule/list";
    }

    @GetMapping("/schedule/delete/{id}")
    public String deleteSchedule(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        adminService.deleteScheduleById(id);
        redirectAttributes.addFlashAttribute("message", "排班删除成功");
        return "redirect:/admin/schedule/list";
    }
    @GetMapping("/schedule/editByDoctorId/{doctor_id}")
    public String editScheduleByDoctorId(@PathVariable Integer doctor_id, Model model) {
        // 假设每个医生只有一个当前排班记录
        Schedule schedule = adminService.findScheduleByDoctorId(doctor_id);

        if (schedule == null) {
            return "error"; // 或者处理找不到的情况
        }

        model.addAttribute("schedule", schedule);
        return "Admin/schedule_edit";
    }



    //床位管理
    // 显示病床列表
    @GetMapping("/bed/list")
    public String listBeds(Model model) {
        List<Bed> beds = adminService.findAllBeds();
        Map<String, List<Bed>> groupedBeds = groupBedsByRoomNumber(beds);
        model.addAttribute("groupedBeds", groupedBeds);
        return "Admin/bed_list";
    }

    // 显示添加表单
    @GetMapping("/bed/add")
    public String showAddBedForm(Model model) {
        model.addAttribute("bed", new Bed());
        return "Admin/bed_form";
    }

    //查询病房号使用情况
    @GetMapping("/bed/search")
    public String searchBeds(@RequestParam("roomNumber") String roomNumber, Model model) {
        System.out.println("搜索病房号: " + roomNumber);
        List<Bed> beds = adminService.findBedsByRoomNumber(roomNumber);
        System.out.println("找到病床数量: " + beds.size());
        Map<String, List<Bed>> groupedBeds = groupBedsByRoomNumber(beds);
        model.addAttribute("groupedBeds", groupedBeds);
        return "Admin/bed_list";
    }

    private Map<String, List<Bed>> groupBedsByRoomNumber(List<Bed> beds) {
        Map<String, List<Bed>> groupedBeds = new HashMap<>();
        for (Bed bed : beds) {
            String roomNumber = bed.getRoomNumber();
            groupedBeds.computeIfAbsent(roomNumber, k -> new ArrayList<>()).add(bed);
        }
        return groupedBeds;
    }

    // 显示编辑表单
    @GetMapping("/bed/edit/{id}")
    public String editBed(@PathVariable Integer id, Model model) {
        model.addAttribute("bed", adminService.findBedById(id));
        return "Admin/bed_form";
    }

    // 保存或更新病床
    @PostMapping("/bed/save")
    public String saveBed(@ModelAttribute Bed bed) {
        if (bed.getId() == null) {
            adminService.saveBed(bed);
        } else {
            adminService.updateBed(bed);
        }
        return "redirect:/admin/bed/list";
    }

    // 删除病床
    @GetMapping("/bed/delete/{id}")
    public String deleteBed(@PathVariable Integer id) {
        adminService.deleteBedById(id);
        return "redirect:/admin/bed/list";
    }



    // 登录与主页
    @GetMapping("/login")
    public String showLoginForm(Model model) {
        model.addAttribute("admin", new Admin());
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String account, @RequestParam String pwd,
                        RedirectAttributes redirectAttributes, HttpSession session) {
        Admin admin = adminService.adminlogin(account);
        if (admin != null) {
            session.setAttribute("admin", admin);
            return "redirect:/admin/index";
        } else {
            redirectAttributes.addFlashAttribute("message", "登录失败");
            return "redirect:/admin/login";
        }
    }

    @GetMapping("/index")
    public String adminIndex(HttpSession session) {
        // 检查 session 中是否存在管理员信息
        Admin admin = (Admin) session.getAttribute("user");
        if (admin == null) {
            throw new RuntimeException("用户未登录或会话已过期");
        }
        return "Admin/AdminIndex";
    }

}
